import express from 'express';
import mysql from 'mysql2';
import bodyParser from 'body-parser';
import cors from 'cors';
import bcrypt from 'bcrypt';  // 导入 bcrypt 库

const app = express();
const port = 3000;

// 设置中间件
app.use(cors());
app.use(bodyParser.json());

// 创建 MySQL 连接
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'mysql'
});

connection.connect((err) => {
    if (err) throw err;
    console.log('Connected to MySQL database.');
});

// 登录接口
app.post('/api/login', (req, res) => {
    const { username, password } = req.body;

    // 查询用户
    connection.query('SELECT * FROM login_info WHERE username = ?', [username], async (err, results) => {
        if (err) {
            return res.status(500).json({ message: 'Database error' });
        }

        if (results.length > 0) {
            // 比较密码
            const user = results[0];
            const match = await bcrypt.compare(password, user.password);
            if (match) {
                res.json({ message: 'Login successful', user });
            } else {
                res.status(401).json({ message: 'Invalid username or password' });
            }
        } else {
            res.status(401).json({ message: 'Invalid username or password' });
        }
    });
});

// 注册 API
app.post('/api/register', async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ message: '用户名和密码不能为空' });
    }

    try {
        // 检查用户是否已存在
        connection.query('SELECT * FROM login_info WHERE username = ?', [username], async (err, results) => {
            if (err) {
                return res.status(500).json({ message: 'Database error' });
            }

            if (results.length > 0) {
                return res.status(400).json({ message: '用户名已存在' });
            }

            // 加密密码
            const hashedPassword = await bcrypt.hash(password, 10);

            // 将用户信息存储到数据库
            connection.query('INSERT INTO login_info (username, password) VALUES (?, ?)', [username, hashedPassword], (err) => {
                if (err) {
                    return res.status(500).json({ message: '数据库插入错误' });
                }
                res.status(201).json({ message: '注册成功' });
            });
        });
    } catch (error) {
        console.error('Register error:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
